package com.hl.security.config;

import com.hl.security.UserAuthenticationFailureHandler;
import com.hl.security.UserAuthenticationSuccessHandler;
import com.hl.security.UserLogoutSuccessHandler;
import com.hl.security.UserServicesImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.BasePasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by aaron on 2017/1/12.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginProcessingUrl("/login_c").failureHandler(userAuthenticationFailureHandler())
                .successHandler(userAuthenticationSuccessHandler())
                .permitAll()
                .and()
                .logout().logoutUrl("/logout").logoutSuccessHandler(userLogoutSuccessHandler())
                .permitAll();
    }

    @Bean
    public UserLogoutSuccessHandler userLogoutSuccessHandler() throws Exception {
        return new UserLogoutSuccessHandler();
    }

    @Bean
    public UserAuthenticationFailureHandler userAuthenticationFailureHandler() throws Exception {
        return new UserAuthenticationFailureHandler();
    }

    @Bean
    public UserAuthenticationSuccessHandler userAuthenticationSuccessHandler() throws Exception {
        return new UserAuthenticationSuccessHandler();
    }

    @Bean
    public UserServicesImpl userServicesImpl() throws Exception {
        return new UserServicesImpl();
    }

    @Bean
    public BasePasswordEncoder passwordEncoder() throws Exception {
        return new ShaPasswordEncoder(256);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userServicesImpl()).passwordEncoder(passwordEncoder());
    }

}
